package cc.laop.support.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Pengpeng on 2017/5/31.
 */
public class ExceptionHandler implements HandlerExceptionResolver {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionHandler.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request,
                                         HttpServletResponse response, Object obj, Exception exception) {
        logger.error(exception.getMessage(), exception);
        String requestType = request.getHeader("X-Requested-With");
        if ("XMLHttpRequest".equals(requestType)) {
            write(response, exception);
        } else {
            ModelAndView mv = new ModelAndView();
            mv.setViewName("/error/error");
            mv.addObject("message", exception.getMessage());
            return mv;
        }
        return null;
    }

    public void write(HttpServletResponse response, Exception exception) {
        PrintWriter out = null;
        try {
            out = response.getWriter();
            Map<String, Object> map = new HashMap();
            map.put("result", -1);
            map.put("message", exception.getMessage());
            ObjectMapper mapper = new ObjectMapper();
            String result = mapper.writeValueAsString(map);
            out.append(result);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
}
